<template>
  <div>
    <ay-aside :page-info="pageInfo" />
    <div class="app-container">
      <div class="filter-container">
        <el-button v-waves class="filter-item refresh-btn" icon="el-icon-refresh" @click="handleRefresh" />
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-button v-waves class="filter-item" type="danger" icon="el-icon-delete" :disabled="disabledDelBtn" @click="handleDelete(delIdArr)">
          删除
        </el-button>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="30"
        />
        <el-table-column label="#" align="center" width="80">
          <template slot-scope="{$index}">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="浮窗名称" width="180px">
          <template slot-scope="{row}">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="浮窗图片" align="center" min-width="300px">
          <template slot-scope="{row}">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.url"
              :preview-src-list="row.src"
            />
          </template>
        </el-table-column>
        <el-table-column label="浮窗链接地址" align="center" min-width="300px">
          <template slot-scope="{row}">
            <template v-if="row.edit">
              <el-input v-model="row.mobile" class="upload-input" size="small" />
              <el-button
                class="input-upload-btn"
                size="small"
                icon="el-icon-upload"
                type="warning"
                @click="cancelEditInput(row)"
              />
            </template>
            <template v-else>
              <span class="edit-span">{{ row.mobile }}</span>
              <el-button
                class="input-edit-btn"
                size="small"
                icon="el-icon-edit"
                type="primary"
                @click="showEditInput(row)"
              />
            </template>
          </template>
        </el-table-column>
        <el-table-column label="显示开关" align="center" width="300px">
          <template slot-scope="{row}">
            <el-switch
              v-model="row.witch"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="handleUpdate(row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="handleDelete([row.userId])" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" class="op-dialog">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 400px; margin-left:50px;">
          <el-form-item label="浮窗名称：" prop="username">
            <el-input v-model="temp.username" placeholder="输入浮窗名称" />
          </el-form-item>
          <el-form-item label="浮窗链接地址：" prop="mobile">
            <el-input v-model="temp.mobile" placeholder="输入浮窗链接地址" />
          </el-form-item>
          <el-form-item label="浮窗图片：" prop="email">
            <el-upload
              class="image-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="image">
              <i v-else class="el-icon-plus image-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="显示开关：" prop="status">
            <template>
              <el-radio v-model="temp.status" :label="0">显示</el-radio>
              <el-radio v-model="temp.status" :label="1">隐藏</el-radio>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="提示"
        :visible.sync="dialogDelVisible"
        width="30%"
      >
        <span>确定删除数据？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogDelVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteData">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getUserList, saveUserInfo, updateUserInfo, deletUserInfo, selectRoleList } from '@/api/privilege'
import { deepClone } from '@/utils/index'
import waves from '@/directive/waves' // waves directive
import AyAside from '@/components/Aside'
import md5 from 'js-md5'
export default {
  name: 'ApplicationFloatingWindow',
  components: { AyAside },
  directives: { waves },
  filters: {},
  data() {
    return {
      isClearable: true, // 下拉树可清空（可选）
      isAccordion: true, // 下拉树可收起（可选）
      props: { // 下拉树配置项（必选）
        value: 'id',
        label: 'name',
        children: 'children',
        disabled: true
      },
      disabledDelBtn: true,
      dialogIconVisible: false,
      dialogDelVisible: false,
      pageInfo: {},
      list: null,
      listLoading: true,
      selectList: null,
      delIdArr: [],
      temp: {
        userId: undefined,
        roleIdList: [],
        username: '',
        email: '',
        mobile: '',
        password: '',
        status: 0
      },
      tableData: [],
      toggleSwitch: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        username: [{ required: true, message: '用户名称不能为空', trigger: 'change' }],
        nickname: [{ required: true, message: '昵称不能为空', trigger: 'change' }],
        password: [
          { required: true, trigger: ['blur', 'change'] }
        ]
      },
      userName: '',
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0
    }
  },
  created() {
    this.getList()
    this.pageInfo = this.$route.meta
  },
  methods: {
    // 获取表格数据接口
    getList() {
      this.listLoading = true
      return new Promise((resolve, reject) => {
        getUserList({
          userName: this.userName,
          createUserId: null,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }).then(response => {
          this.list = response.data.list
          this.pageTotal = response.data.total
          this.pageSize = response.data.pageSize
          this.pageNum = response.data.pageNum
          const cloneData = deepClone(this.list)
          selectRoleList({}).then((response) => {
            this.selectList = response.data
          })
          this.tableData = cloneData
          for (const i in this.tableData) {
            const roleIdListTemp = []
            const roleNameListTemp = []
            this.tableData[i].edit = false
            for (const j in this.tableData[i].sysRoleDTOList) {
              roleIdListTemp.push(this.tableData[i].sysRoleDTOList[j].roleId)
              roleNameListTemp.push(this.tableData[i].sysRoleDTOList[j].roleName)
            }
            this.tableData[i].roleIdList = roleIdListTemp
            this.tableData[i].roleNameList = roleNameListTemp
          }
          this.listLoading = false
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
            resolve(true)
          }, 500)
        }).catch(error => {
          this.$message({
            message: error,
            type: 'error'
          })
          reject(false)
        })
      }
      )
    },
    // 刷新
    async handleRefresh() {
      if (await this.getList()) {
        this.$message({
          message: '刷新成功',
          type: 'success'
        })
      }
    },
    // 新增操作
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 表格选中时触发
    handleSelectionChange(selection) {
      this.delIdArr = []
      if (selection.length) {
        this.disabledDelBtn = false
        for (const i in selection) {
          this.delIdArr.push(selection[i].userId)
        }
      } else {
        this.disabledDelBtn = true
      }
    },
    // 初始化表单
    resetTemp() {
      this.temp = {
        userId: undefined,
        roleIdList: [],
        username: '',
        email: '',
        mobile: '',
        password: '',
        status: 0
      }
    },
    // 新增数据接口
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp, 'temp')
          this.temp.password = md5(this.temp.password)
          saveUserInfo(this.temp).then((response) => {
            this.$message({
              message: '新增成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 编辑操作
    handleUpdate(row) {
      console.log(row, 'rrr')
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.temp.password = null
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据接口
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.password !== null) {
            this.temp.password = md5(this.temp.password)
          }
          updateUserInfo(this.temp).then((response) => {
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 删除操作
    handleDelete(idArr) {
      this.dialogDelVisible = true
      this.delIdArr = idArr
    },
    deleteData() {
      deletUserInfo(this.delIdArr).then(() => {
        this.dialogDelVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    // 显示编辑框
    showEditInput(row) {
      console.log(row, 'showEditInput')
      row.edit = true
    },
    // 显示编辑框
    cancelEditInput(row) {
      console.log(row, 'cancelEditInput')
      row.edit = false
    },
    // 上传图片成功
    handleImageSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 上传图片前
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss">
.app-container {
  .el-table {
    .gray-row {
      color: #c2d2d2;
    }
    .input-upload-btn {

    }
    .upload-input {
      width: 82%;
    }
    .edit-span {
      display: inline-block;
      width: 82%;
    }
    .input-edit-btn {

    }
  }
  .el-button--mini{
    padding: 7px;
  }
  .filter-container{
    .filter-item {
      margin-left: 0;
      &.refresh-btn{
        background-color: #030303;
        color: azure;
      }
    }
  }
  .op-dialog {
    .image-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .image-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .image {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>
